package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.client.SearchFeign;
import cn.itsource.hrm.config.RabbitmqConfig;
import cn.itsource.hrm.document.CourseDoc;
import cn.itsource.hrm.domain.Course;
import cn.itsource.hrm.domain.CourseDetail;
import cn.itsource.hrm.domain.CourseMarket;
import cn.itsource.hrm.domain.dto.SaveCourseDTO;
import cn.itsource.hrm.dto.SendEmail;
import cn.itsource.hrm.dto.SendInner;
import cn.itsource.hrm.dto.SendSMS;
import cn.itsource.hrm.exception.GloabException;
import cn.itsource.hrm.mapper.CourseDetailMapper;
import cn.itsource.hrm.mapper.CourseMapper;
import cn.itsource.hrm.mapper.CourseMarketMapper;
import cn.itsource.hrm.service.ICourseService;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.ValidityUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static cn.itsource.hrm.constant.RabiitMQConstant.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gwkge
 * @since 2021-04-03
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    RabbitTemplate rabbitTemplate;  // 用于发送消息到消息队列中的
    
    @Autowired
    private SearchFeign searchFeign;

    @Autowired
    private CourseDetailMapper detailMapper;
    
    @Autowired
    private CourseMarketMapper marketMapper;
    
    @Override
    public void save(SaveCourseDTO saveCourseDTO) {
        //1. 获取课程信息，课程详细，课程营销数据
        Course course = saveCourseDTO.getCourse();
        CourseDetail detail = saveCourseDTO.getCourseDetail();
        CourseMarket market = saveCourseDTO.getCourseMarket();
        
        //2. 判断业务（非空已经 JSR303 ）都可以重复 
        
        
        //3. 保存，三张表是一对一的关系，同时保存就可以了
        //一定要注意，自己手动添加默认值
        course.setStatus(Course.COURSE_OFFLINE);
        // 准备假数据 TODO 后面认证之后完成
        
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println(authentication.getAuthorities());
        String name = authentication.getName();
        System.out.println("用户名： "+name);
        Object principal = authentication.getPrincipal();
        System.out.println("principal: "+principal);
            

        course.setUserName("贾宝玉");
        course.setUserId(1L);
        course.setTenantName("源码时代");
        course.setTenantId(1L);
        
        baseMapper.insert(course);
        
        // 保存课程详情
        detail.setId(course.getId());
        detailMapper.insert(detail);
        
        // 保存课程营销数据
        market.setId(course.getId());
        marketMapper.insert(market);
        
    }

    @Override
    @Transactional
    public void onLineCourse(Long id) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("authentication： "+authentication.getAuthorities());
        String name = authentication.getName();
        System.out.println("用户名： "+name);
        Object principal = authentication.getPrincipal();
        System.out.println("principal: "+principal);
        
        
        //根据id 查询状态，是否已经是上线了的，如果已上线直接抛自定义全局异常
        Course course = baseMapper.selectById(id);
        ValidityUtils.isNotNull(course,"课程不存在");
        ValidityUtils.isNotEquals(course.getStatus(),Course.COURSE_ONLINE,"课程已上线");
       
        //如果没有上线，修改数据库中的状态
        course.setStatus(Course.COURSE_ONLINE);
        baseMapper.updateById(course);
        
        //修改成功，之后在把课程添加到ElasticSearch中
        CourseDoc courseDoc = new CourseDoc();
        CourseDetail detail = detailMapper.selectById(course.getId());
        CourseMarket market = marketMapper.selectById(course.getId());
        
        BeanUtils.copyProperties(course, courseDoc);
        BeanUtils.copyProperties(market, courseDoc);
        BeanUtils.copyProperties(detail, courseDoc);
        if(market.getCharge().equals(CourseMarket.FREE)){
            courseDoc.setChargeName("免费");
        }else {
            courseDoc.setChargeName("收费");
        }
        courseDoc.setOnLineTime(new Date());

        // 通过 feign 接口，调用SearchServer 服务，实现课程的添加的ES中。
        AjaxResult ajaxResult = searchFeign.onLineCourse(courseDoc);
        ValidityUtils.isTrue(ajaxResult.isSuccess(),"服务器异常，我们真正抢修中....");

        //如果添加成功，通知订阅机构的 用户  
        sendMessages(course);

    }

    private void sendMessages(Course course) {
        //先发送 短信 ：电话，内容
        List<String> phones = Arrays.asList("13800006666","1598886666","16855559999");
        String conent = "亲爱的用户，我们课程【%s】课程已经上线，请查收。【%S】";
        String mssage = String.format(conent, course.getName(), course.getTenantName());

        rabbitTemplate.convertAndSend(EXCHANGE_DIRECT_INFORM,
                ROUTING_KEY_SMS, new SendSMS(phones,mssage));
        
        
        //先发送 邮件 ：邮箱，内容
        List<String> email = Arrays.asList("1380000@qq.com","159888@qq.com","1685555@qq.com");
        String email_conent = "亲爱的用户，我们课程【%s】课程已经上线，<a href='http://www.itsource.com'>请查收。【%S】";
        String email_mssage = String.format(email_conent, course.getName(), course.getTenantName());

        rabbitTemplate.convertAndSend(EXCHANGE_DIRECT_INFORM,
                ROUTING_KEY_EMAIL, new SendEmail(email,email_mssage));
        
        
        //先发送 站内信 ：电话，内容
        List<Long> users = Arrays.asList(138006L,1598L,999L);
        String title = "你订阅的课程已经上线，请查收";
        rabbitTemplate.convertAndSend(EXCHANGE_DIRECT_INFORM,
                ROUTING_KEY_INNER, new SendInner(users,title,mssage,new Date()));
        
        
        
    }


}
